import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, useAccess, history, useModel } from '@umijs/max';
import { Button, message, Modal, Dropdown, FormInstance, Space, Switch, Tag } from 'antd';
import { ActionType, FooterToolbar, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, DownOutlined } from '@ant-design/icons';
import UpdateForm from './components/AssetForm';
import { getAssetList,addAsset, updateAsset, removeAsset} from '@/services/manage/asset';
import dayjs from 'dayjs';

const { confirm } = Modal;

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: API.Manage.Asset) => {
  const hide = message.loading('正在添加');
  try {
    const resp = await addAsset({ ...fields });
    hide();
    if (resp.code === 200) {
      message.success('添加成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.Manage.Asset) => {
  const hide = message.loading('正在更新');
  try {
    const resp = await updateAsset(fields);
    hide();
    if (resp.code === 200) {
      message.success('更新成功');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }
};

/**
 * 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.Manage.Asset[]) => {
  // console.log(selectedRows);  
  const hide = message.loading('正在删除');  
  if (!selectedRows) return true;
  try {
    const resp = await removeAsset(selectedRows.map((row) => row.assetId))
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleRemoveOne = async (selectedRow: API.Manage.Asset) => {
  console.log(selectedRow);  
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    const params = [selectedRow.assetId];
    console.log(params)
    const resp = await removeAsset(params);
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const AssetTable: React.FC = () => {

  const [messageApi, contextHolder] = message.useMessage();
  const formTableRef = useRef<FormInstance>();

  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [dataScopeModalOpen, setDataScopeModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Manage.Asset>();
  const [selectedRows, setSelectedRows] = useState<API.Manage.Asset[]>([]);
  const [pageSize, setPageSize] = useState(10);

  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser; 

  const access = useAccess();

  /** 国际化配置 */
  const intl = useIntl();

  useEffect(() => {
    // console.log('currentUser',currentUser);    
  }, [])

  const columns: ProColumns<API.Manage.Asset>[] = [
    {
      title: "资产编号" ,
      dataIndex: 'assetId',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
      sorter: (a, b) => a.assetId - b.assetId,
      defaultSortOrder: 'descend',
    },
    {
      title: "设备名称" ,
      dataIndex: 'deviceName',
      valueType: 'text',
      align: 'center',
      // hideInSearch: true,
    },
    {
      title: "设备编号",
      dataIndex: 'deviceNum',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: "IP地址",
      dataIndex: 'ipAddress',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: "设备类型" ,
      dataIndex: 'deviceType',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
        title:"在线状态",
        dataIndex: 'isOnline',
        valueType: 'select',
        align: 'center',
        valueEnum:  {
            0: { text: '离线', status: 'error' },
            1: { text: '在线', status: 'success' }
          },
        render: (_, record) => {
            return (
            <Switch
                checked={record.isOnline === 1}
                checkedChildren="在线"
                unCheckedChildren="离线"
                defaultChecked
            />)
        }
    },
    {
      title: "网络状态",
      dataIndex: 'networkStatus',
      valueType: 'select',
      align: 'center',
      valueEnum: {
        0: { text: '异常', status: 'error' },
        1: { text: '正常', status: 'success' },
      },
      render: (_, record) => {
        // 定义状态映射
        const statusMap : Record<number, { color: string; text: string }>= {
          0: { color: 'red', text: '异常' },
          1: { color: 'green', text: '正常' },
        };
        return (
          <Tag color={statusMap[record.networkStatus].color}>
            {statusMap[record.networkStatus].text}
          </Tag>
        );
      },
    },
    {
      title: "电池电量" ,
      dataIndex: 'batteryLevel',
      valueType: 'progress',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: "最后在线时间",
      dataIndex: 'lastOnline',
      valueType: 'dateTime',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        const formattedTime = record.lastOnline 
          ? dayjs(record.lastOnline).format('YYYY-MM-DD HH:mm:ss')
          : '-';
        return <span>{formattedTime}</span>;
      },
    },
    {
      title: "创建时间" ,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        const formattedTime = record.createTime 
          ? dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss')
          : '-';
        return <span>{formattedTime}</span>;
      },
    },
    {
      title: "更新时间" ,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      align: 'center',
      hideInSearch: true,
      render: (_, record) => {
        const formattedTime = record.updateTime 
          ? dayjs(record.updateTime).format('YYYY-MM-DD HH:mm:ss')
          : '-';
        return <span>{formattedTime}</span>;
      },
    },
    {
      title: "操作" ,
      dataIndex: 'option',
      width: '220px',
      align: 'center',
      valueType: 'option',
      render: (_, record) => [
        <Button
          type="link"
          size="small"
          key="edit"
          icon=<EditOutlined />
          hidden={!access.hasPerms('inspection:asset:edit')}
          onClick={() => {
            setCurrentRow(record);
            setModalVisible(true);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          key="delete"
          icon=<DeleteOutlined />
          hidden={!access.hasPerms('inspection:asset:removes')}
          onClick={async () => {
            Modal.confirm({
              title: '删除',
              content: '确定删除该资产吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const success = await handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer>
      {contextHolder}
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.Manage.Asset>
          headerTitle='查询资产表格'
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="assetId"
          key="assetList"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('inspection:asset:add')}
              onClick={async () => {
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
            </Button>,
            <Button
              type="primary"
              key="remove"
              danger
              hidden={selectedRows?.length === 0 || !access.hasPerms('inspection:role:removes')}
              onClick={async () => {
                Modal.confirm({
                  title: '是否确认删除所选数据项?',
                  icon: <ExclamationCircleOutlined />,
                  content: '请谨慎操作',
                  async onOk() {
                    const success = await handleRemove(selectedRows);
                    if (success) {
                      setSelectedRows([]);
                      actionRef.current?.reloadAndRest?.();
                    }
                  },
                  onCancel() { },
                });
              }}
            >
              <DeleteOutlined />
              <FormattedMessage id="pages.searchTable.delete" defaultMessage="删除" />
            </Button>,
          ]}
          request={(params) =>  {      
            const { current, ...rest } = params;
            const queryParams = {
              pageNum: current,       // 将 current 映射为 pageNum
              pageSize: params.pageSize,
              ...rest,
            };
            return getAssetList(queryParams as API.Manage.AssetListParams).then((res) => {
              console.log(params)   //{current: 1, pageSize: 10}
              const result = {
                data: res.rows,
                total: res.total,
                success: true,
              };
              return result;
            })}
          }
          columns={columns}
          columnsState={{
            persistenceKey: 'inspection-table',
            persistenceType: 'localStorage',
            defaultValue: {
              updateTime: {show: false  }, // ✅ 默认隐藏，但用户可手动勾选
              createTime: {show: false  },
            },
          }}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
          pagination={{
            pageSize,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
              setPageSize(size);
            },
          }}
        />
      </div>
      {selectedRows?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />
              <a style={{ fontWeight: 600 }}>{selectedRows.length}</a>
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            key="remove"
            danger
            hidden={!access.hasPerms('inspection:asset:removes')}
            onClick={async () => {
              Modal.confirm({
                title: '删除',
                content: '确定删除该项吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  const success = await handleRemove(selectedRows);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
        </FooterToolbar>
      )}
      <UpdateForm
        onSubmit={async (values) => {
          let success = false;
          if (values.assetId) {
            console.log('UpdateForm values:', values);            
            success = await handleUpdate({ ...values } as API.Manage.Asset);
          } else {
            console.log('AddForm values:', values);            
            success = await handleAdd({ ...values } as API.Manage.Asset);
          }
          if (success) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        open={modalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default AssetTable;